import React from 'react';
import { Spin, TreeSelect } from 'antd';
import { getClassTree, getClassTreeDirFromDb, getClassTreeTop } from '@/services/goods/class';

type ClassTreeSelectProps = {
  type: 'top' | 'dir' | 'all';
  value?: number;
  onChange?: (value: number | undefined) => void;
  width?: 'md';
};

const getClassFuns = {
  top: getClassTreeTop,
  dir: getClassTreeDirFromDb,
  all: getClassTree,
};

/**
 * 这个组件的作用是为了显示一级组件，可以返回classId与className,所以在外围form中，就不用定义classId与className了
 * @param props 参数
 */
const ClassTreeSelect: React.FC<ClassTreeSelectProps> = (props: ClassTreeSelectProps) => {
  const { type, value, onChange } = props;

  // 得到商品分类下拉框的数据
  const [dataSource, setDataSource] = React.useState<any[] | undefined>(undefined);

  const getClassFun = getClassFuns[type];

  /**
   * 读取取数据库中的数据，并刷新页面
   */
  React.useEffect(() => {
    const initFun = async () => {
      // 检索出数据
      const result = await getClassFun();
      if (result.success) {
        setDataSource(result.data.children);
      }
    };
    initFun();
  }, []);

  const onChangeHandle = (currentValue: number) => {
    if (onChange) {
      onChange(currentValue);
    }
  };

  const width = { width: '328px' };

  if (!dataSource) {
    return <Spin />;
  }

  return (
    <TreeSelect
      style={{ ...width }}
      dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
      treeData={dataSource}
      defaultValue={value}
      onChange={onChangeHandle}
      allowClear
    />
  );
};

ClassTreeSelect.defaultProps = {};

export default ClassTreeSelect;
